package com.online.controller;

import com.alibaba.fastjson.JSONObject;
import com.online.entity.*;
import com.online.service.*;
import com.online.utils.emailCode.EmailManage;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.WritableWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/teacher")
public class TeacherController {

    @Autowired
    TeacherService teacherService;

    @Autowired
    ExamService examService;

    @Autowired
    CEService ceService;

    @Autowired
    PaperService paperService;

    @Autowired
    BlankService blankService;

    @Autowired
    OptionService optionService;

    @Autowired
    StudentService studentService;

    @Autowired
    UserService userService;

    /**
     * 教师上传excel文件的入口并导入数据
     *
     * @return
     */
    @RequestMapping(value = "/uploadExcel", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String upload(HttpSession session, MultipartFile file, HttpServletRequest httpServletRequest) throws IOException{

        //设置教师选择的班级
        String studentClass = httpServletRequest.getParameter("studentClass");

        session.setAttribute("studentClass", studentClass);

        List<Student> studentList = new ArrayList<>();

        //获取文件的服务器路径
        String realPath = httpServletRequest.getSession().getServletContext().getRealPath("/excels/excel/");

        //获取上传文件的名字
        String fileName = file.getOriginalFilename();

        //判断文件的后缀名
        if (!fileName.endsWith("xlsx") && !fileName.endsWith("xls")) {
            httpServletRequest.setAttribute("result", "文件不为excel文件禁止上传");
            return "teacher/upload_fail";
        }

        //判断工作簿是否存在，不存在则创建工作簿
        File excelFile = new File(realPath + fileName);

        //删除已存在的工作簿
        if (excelFile.exists()) {
            boolean b = excelFile.delete();
            System.out.println(b);
        }

        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) file;

        //新建2003excel工作簿并读取数据
        if (!excelFile.exists() && fileName.endsWith("xls") || fileName.endsWith("xlsx")) {

            if (fileName.endsWith("xlsx")) {

                //判断工作簿是否存在，不存在则创建工作簿
                File xssfFile = new File(realPath + fileName);

                //删除已存在的工作簿
                if (xssfFile.exists()) {
                    boolean b = excelFile.delete();
                    System.out.println(b);
                }

                //新建工作簿
                WritableWorkbook workbook = Workbook.createWorkbook(xssfFile);

                try {
                    //将上传工作簿的内容写入到服务器中新建的工作簿
                    commonsMultipartFile.getFileItem().write(xssfFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //读取工作簿的数据
                XSSFWorkbook book = null;
                //获取文件流对象
                book = new XSSFWorkbook(new FileInputStream(xssfFile));
                //获取第一个标签
                XSSFSheet sheet = book.getSheetAt(0);

                //获取第一行
                int firstRow = sheet.getFirstRowNum();
                System.out.println("第一行" + firstRow);
                //获取最后一行
                int lastRow = sheet.getLastRowNum();
                System.out.println("最后一行" + lastRow);

                //遍历行
                for(int i = firstRow; i <= lastRow; i++) {
                    //获取每一行的列
                    Row row = sheet.getRow(i);

                    if(row != null) {
                        System.out.println(row.getCell(0).toString());
                        System.out.println(row.getCell(1).toString());

                        Student student = new Student();
                        student.setStudentName(row.getCell(0).toString());
                        student.setPassword(row.getCell(1).toString());
                        student.setStudentNumber(row.getCell(1).toString());
                        studentList.add(student);
                    }
                }

            } else {

                //读取2007版本以下的数据
                WritableWorkbook workbook = Workbook.createWorkbook(excelFile);

                try {
                    //将上传工作簿的内容写入到服务器中新建的工作簿
                    commonsMultipartFile.getFileItem().write(excelFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //读取数据
                File readfile = new File(realPath + fileName);
                System.out.println(fileName);
                InputStream inputStream = null;

                try {
                    //创建输入流读取文件
                    inputStream = new FileInputStream(readfile.getAbsolutePath());
                    Workbook w = Workbook.getWorkbook(inputStream);
                    //excel的页签数量
                    int sheet_size = w.getNumberOfSheets();
                    // Excel的页签数量
                    for (int index = 0; index < sheet_size; index++) {
                        // 每个页签创建一个Sheet对象
                        Sheet sheet = w.getSheet(index);
                        // sheet.getRows()返回该页的总行数
                        for (int i = 0; i < sheet.getRows(); i++) {

                            //获取学号和密码

                            String studentNumber = sheet.getCell(1, i).getContents();

                            Student student = new Student();
                            student.setStudentName(sheet.getCell(0, i).getContents());
                            student.setStudentNumber(sheet.getCell(1, i).getContents());
                            student.setPassword(studentNumber);
                            //将student添加进List集合
                            studentList.add(student);
                        }
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (BiffException e) {
                    e.printStackTrace();
                }
                inputStream.close();
            }
        }

        // 判断新建的工作簿是否存在
        if (excelFile.exists()) {
            session.setAttribute("studentList", studentList);
            httpServletRequest.setAttribute("result", "你想要导入的数据");
            return "teacher/upload_result";
        } else {
            httpServletRequest.setAttribute("result", "上传失败");
            return "teacher/upload_fail";
        }
    }


    /**
     * 查询教师的个人信息
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getTeacherInfo", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getTeacherInfo(HttpServletRequest httpServletRequest) {

        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();

        //获取老师的工号
        String workNumber = (String) subject.getPrincipal();
        System.out.println("workNumber:" + workNumber);

        Teacher teacher = teacherService.showATeacher(workNumber);

        httpServletRequest.setAttribute("teacher", teacher);

        return "teacher/teacher_info";

    }

    /**
     * 教师更新个人信息
     *
     * @param teacherId
     * @param username
     * @param password
     * @param email
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateTeacherInfo", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String updateTeacherInfo(@RequestParam(value = "teacherId", required = false) Integer teacherId,
                                    @RequestParam(value = "username", required = false) String username,
                                    @RequestParam(value = "password", required = false) String password,
                                    @RequestParam(value = "email", required = false) String email) {

        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();

        //获取userNumber
        String userNumber = (String) subject.getPrincipal();

        //更新教师基本信息
        int result = teacherService.updateTeacher(teacherId, username, password, email);

        //更新教师的登录信息
        result = userService.updateUserByUserNumber(userNumber, password);

        if (result != 0) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("更新成功");
            System.out.println(correctJsonObject);
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101, "更新失败");
            System.out.println(errorJsonObject);
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 教师获取验证码入口
     *
     * @param httpServletRequest
     */
    @RequestMapping(value = "/getVerificationCode", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String getVerificationCode(HttpServletRequest httpServletRequest) {

        //获取教师的邮箱
        String eamil = httpServletRequest.getParameter("email");

        //查询邮箱是否已被注册
        boolean b = teacherService.findTeacherByEmail(eamil);

        //教师没有被注册
        if(b == false) {

            //调用邮箱工具发送验证码
            EmailManage emailManage = new EmailManage(eamil);
            //发送验证码
            emailManage.addEmail();

            httpServletRequest.setAttribute("email", eamil);

            return "teacher/register";
        }else {
            //教师已注册则返回提示信息
            httpServletRequest.setAttribute("error","邮箱已被注册");
            return "teacher/getVerificationCode";
        }
    }

    /**
     * 验证邮箱是否被注册及返回教师更新密码界面
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/vertifyEmail",method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
    public String VertifyEmail(HttpServletRequest httpServletRequest) {

        //获取邮箱
        String email = httpServletRequest.getParameter("email");

        //查询邮箱是否存在
        boolean b = teacherService.findTeacherByEmail(email);

        //用户不存在
        if(b == false) {
            httpServletRequest.setAttribute("error","此邮箱未被注册");
            return "teacher/reset_password";

            //邮箱被注册则返回重置密码页面
        }else {
            httpServletRequest.setAttribute("email",email);
            //用户存在
            return "teacher/update_password";
        }
    }

    /**
     * 教师注册入口
     *
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String teacherRegister(HttpServletRequest httpServletRequest) {

        //获取教师邮箱
        String email = httpServletRequest.getParameter("email");
        //获取教师的验证码
        System.out.println(email);

        String code = httpServletRequest.getParameter("code");
        System.out.println(code);

        String verfitication = null;

        try {
            verfitication = EmailManage.getEmail(email).getMailCheckString();
            System.out.println(verfitication);

        } catch (NullPointerException e) {
            System.out.println("空指针异常");
        }

        //判断用户验证码是否正确
        if (!code.equals(verfitication)) {
            httpServletRequest.setAttribute("error", "验证码错误");
            return "teacher/register";
        }

        //获取教师工号
        String workNumber = httpServletRequest.getParameter("workNumber");
        //获取密码
        String password = httpServletRequest.getParameter("password");

        //插入教师数据
        int result = teacherService.insertATeacher(workNumber, password, email);

        //向user表中插入教师的登录信息
        if (result == 1) {
            User user = new User();
            user.setUserNumber(workNumber);
            user.setPassword(password);
            user.setRole("teacher");
            user.setStatus(0);

            result = userService.addARecord(user);
        }

        if (result != 0) {
            httpServletRequest.setAttribute("error", "注册成功");
            return "user/userLogin";
        } else {
            httpServletRequest.setAttribute("error", "注册失败，请重新开始注册流程");
            return "user/userLogin";
        }
    }

    /**
     * 查询选择题的知识点
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showOPK", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String showOPknowledge() {

        List<Option> list = optionService.showOptionKnowledge();

        if (!list.isEmpty()) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(list);
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101, "查询为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 返回查询的选择题知识点的总数
     *
     * @param knowledge
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "showOptionNumbers", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String showOptionNumbers(@RequestParam(value = "knowledge", required = false) String knowledge) {

        int amount = optionService.countOption(knowledge);

        CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(amount);
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 查询填空题的知识点
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showBlankKno", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String showBlankkno() {

        List<Blank> blanks = blankService.showKnoFoBlank();

        if (!blanks.isEmpty()) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(blanks);
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(301, "查询为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 查询填空题某一知识点总数
     *
     * @param knowledge
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showBlankNumbers", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String showBlankNumbers(@RequestParam(value = "knowledge", required = false) String knowledge) {

        List<Blank> list = blankService.showBlankByKnowledge(knowledge);

        CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(list.size());
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 下载文件
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/downloadPaper", method = RequestMethod.GET, produces = "text/html")
    public void downloadPaper(HttpServletRequest request, HttpServletResponse response) {

        String fileName = request.getParameter("fileName");

        //获取服务器路径
        String realPath = request.getSession().getServletContext().getRealPath("/word/");

        try {
            //设置文件响应头
            response.setHeader("content-disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));

            HttpHeaders headers = new HttpHeaders();
            //通知浏览器以attachment（下载方式）打开文件
            headers.setContentDispositionFormData("attachment", fileName);
            //读取文件,保存到文件输入流
            FileInputStream inputStream = new FileInputStream(realPath + fileName);

            //创建文件输出流
            OutputStream outputStream = response.getOutputStream();

            byte buffer[] = new byte[2014];

            int len = 0;

            while ((len = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }

            inputStream.close();
            outputStream.close();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        System.out.println("下载成功");

        //下载成功删除服务器上的文件
        File file = new File(realPath + fileName);
        if(file.exists()) {
            file.delete();
        }
    }

    /**
     * 教师忘记密码,根据email更新密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/updatePassword",method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
    public String updatePassword(HttpServletRequest request) {

        //获取email,password
        String email = request.getParameter("email");
        String password = request.getParameter("newPassword");
        System.out.println(password);
        //更新教师的登录密码
        boolean result = teacherService.updatePassword(email,password);

        if(result == true) {
            request.setAttribute("error","更新成功!");
            return "user/userLogin";
        }else {
            request.setAttribute("error","更新失败,请重试!");
            return "teacher/update_password";
        }
    }
}






